#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/2/14
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R42_TX_EntTaxCreditRatingCheck_GZ
# @Software  :PyCharm


import json
import re
import sys
import datetime
import pandas as pd
import math

'''eof
name:企业纳税纳税信用等级校验
code:R42_TX_EntTaxCreditRatingCheck_GZ
tableName:
columnName:
groups:场景业务校验-税务
dependencies:TX_GZ_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


# reload(sys)
# sys.setdefaultencoding('utf-8')


def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo


def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_GZ_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]

    except:
        return [{}]


def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def entTaxCreditRatingCheck(CcrDate=None):
    """
    企业税务信用等级需在C级（含）以上，不包括M级的企业通过，否则拒绝。
    根据申请年份：
	税务纳税评级新增当年纳税评级的判断，优先判断，若当年纳税评级为D，则直接拒绝；
	根据申请月份：
    A、如果申请月份>5,取“当前年度-1”和“当前年度-2”,两年评级均大于等于C级才允许通过，否则拒绝。
    B、如果申请月份<=5,优先去取“当前年度-1”和“当前年度-2”，计算方法同上一条；
    如“当前年度-1”无数据，则取“当前年度-2”和“当前年度-3”，此时两年评级均大于等于C级才允许通过，否则拒绝。

    :param CcrDate: 测试时间，默认为None，
    :return:
    """

    if CcrDate is None:
        CcrMonth = datetime.datetime.now().month
        CcrYear = datetime.datetime.now().year
    else:
        # 用于分析
        CcrDate = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date()
        CcrMonth = CcrDate.month
        CcrYear = CcrDate.year

    syptSwpjxx = formatData('syptSwpjxx')

    if syptSwpjxx == [{}]:
        return u'缺失值'
    else:
        syptSwpjxx = pd.DataFrame(syptSwpjxx).dropna(how='all')
        if str(CcrYear) in list(syptSwpjxx['SWXYPJSJ']):
            SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear)]['SWXYPJ'].iloc[-1], 'str')
        elif str(CcrYear-1) in list(syptSwpjxx['SWXYPJSJ']) and CcrMonth > 5:
            SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear-1)]['SWXYPJ'].iloc[-1], 'str')
        elif str(CcrYear-1) in list(syptSwpjxx['SWXYPJSJ']) and CcrMonth <= 5:
            SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear - 1)]['SWXYPJ'].iloc[-1], 'str')
        elif str(CcrYear-2) in list(syptSwpjxx['SWXYPJSJ']) and CcrMonth <= 5:
            SWXYPJSJLastOne = convertDataType(syptSwpjxx[syptSwpjxx['SWXYPJSJ'] == str(CcrYear - 2)]['SWXYPJ'].iloc[-1], 'str')
        else:
            SWXYPJSJLastOne = None

        # 纳税等级校验
        if SWXYPJSJLastOne is None:
            return 0
        else:
            if SWXYPJSJLastOne in [u'M',u'C', u'B', u'A']:
                Factor = 1
            else:
                Factor = 0

            return Factor


result = entTaxCreditRatingCheck()

# try:
#     if __name__ == '__main__':
#         # 下面添加需要执行的函数
#         # 读取json文件
#         file_obj = open(r'G:\\BBDWork\\project\\modelMigration\\data\\TX_CQ_DSJ.js', 'r')
#         content = file_obj.read()
#         TX_CQ_DSJ = json.loads(content, strict=False)['TX_CQ_DSJ']
#
#         # 审批时间
#         spDateTime = '20170812'
#
#         # 连续性纳税校验
#         aa = entTaxCreditRatingCheck()
#         # aa = entTaxCreditRatingCheck(spDate=spDateTime)
#         pass
# except Exception as e:
#     print('exception happen')
#     raise e